package com.kushe.dao;



import com.kushe.config.Config;
import com.kushe.entity.Group;
import com.kushe.entity.Topics;
import com.kushe.util.core.DbUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;


import java.util.List;

/**
 * Created by WSDevotion on 2015/5/2.
 */
public class TopicsDao {
    public static Topics get(int id) {
        return DbUtils.getNutzDao().fetch(Topics.class, id);
    }


    public static Topics addTopics(Topics topics) {
        Dao dao = DbUtils.getNutzDao();
        Group groups = dao.fetch(Group.class, topics.getGroup_id());
        if (groups != null) {
            dao.insert(topics);
            return topics;
        } else
            return null;
    }


    public static QueryResult getByTime(int pageNumber, int [] group_id) {
        Dao dao = DbUtils.getNutzDao();
        Pager pager = dao.createPager(pageNumber, Config.PAGE_SIZE);
        List<Topics> list = null;
        if(group_id[0]==0) {
            list = dao.query(Topics.class, Cnd.orderBy().desc("update_time"), pager);
            pager.setRecordCount(dao.count(Topics.class));
        }else{
            //System.out.println(s);
            Criteria cri = Cnd.cri();
            cri.where().andInIntArray("group_id", group_id);
            cri.getOrderBy().desc("update_time");
            list = dao.query(Topics.class, cri, pager);
            pager.setRecordCount(dao.count(Topics.class, cri));
        }
        return new QueryResult(list, pager);
    }

    public static void deleteTopics(int id){
        Dao dao = DbUtils.getNutzDao();
        dao.delete(Topics.class, id);
    }


    public static List<Topics> getTopicsByUser_id(int user_id){
        return DbUtils.getNutzDao().query(Topics.class, Cnd.where("author_id", "=", user_id));
    }

    public static QueryResult getByHot(int pageNumber, int [] group_id) {
        Dao dao = DbUtils.getNutzDao();
        Pager pager = dao.createPager(pageNumber, Config.PAGE_SIZE);
        List<Topics> list = null;
        if(group_id[0]==0) {
            list = dao.query(Topics.class, Cnd.orderBy().desc("zan"), pager);
        }else{
            String s = "";
            for(int i=0; i<group_id.length-1; i++) {
                s = s + group_id[i] + ",";
            }
            s = s + group_id[group_id.length-1];
            Criteria cri = Cnd.cri();
            cri.where().andIn("group_id", s);
            cri.getOrderBy().asc("zan");
            list = dao.query(Topics.class, cri, pager);

            //list = dao.query(Topics.class, Cnd.cri().where().andIn("group_id", s)..asc("zan"), pager);
        }
        pager.setRecordCount(dao.count(Topics.class));
        return new QueryResult(list, pager);
    }



    public static void updateTopics(Topics topics){
        Dao dao = DbUtils.getNutzDao();
        dao.update(topics);
    }
}
